<template>
  <div class="drawer-container-scroll">
    <el-form ref="caseForm" :model="caseForm" :rules="caseFormRules" :inline="true">
      <el-row>
        <el-form-item label="标题" prop="title">
          <el-input v-model="caseForm.title" placeholder="请输入用例标题" style="width: 180px;" />
        </el-form-item>
        <el-form-item label="目录" prop="catalog_id">
          <SelectTree
            ref="treeSelect"
            v-model="caseForm.catalog_id"
            :data="catalogOptions"
            :common-props="{
              id: 'id',
              name: 'name',
              children: 'children'
            }"
            :filterable="true"
            :default-expand-all="false"
          />
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-select v-model="caseForm.level">
            <el-option
              v-for="item in levelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="版本" prop="version_id">
          <el-select v-model="caseForm.version_id" :disabled="submitType===1">
            <el-option
              v-for="item in verOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="caseForm.status">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="caseForm.desc" type="textarea" :rows="1" placeholder="请输入描述" style="width: 180px;" />
        </el-form-item>
      </el-row>

    </el-form>
    <el-tabs v-model="activeName" value="info" @tab-click="handleTabClick">
      <el-tab-pane label="基本信息" name="info">
        <el-form>
          <el-form-item label="前置条件" prop="precondition">
            <el-input v-model="caseForm.precondition" type="textarea" autosize placeholder="请输入前置条件" />
          </el-form-item>
          <el-form-item label="用例步骤">
            <el-table
              ref="dragTable"
              row-key="num"
              highlight-current-row
              :data="steps"
              :header-cell-style="{ background: '#fafafa' }"
              style="width: 100%"
            >
              <el-table-column align="center" type="index" width="50">
                <template slot-scope="{}">
                  <svg-icon class="drag-handler" icon-class="drag" />
                </template>
              </el-table-column>
              <el-table-column type="index" label="步骤" width="50" />
              <el-table-column label="执行动作" prop="action">
                <template slot-scope="scope">
                  <template>
                    <el-input
                      v-model="scope.row.action"
                      autosize
                      type="textarea"
                      placeholder="执行动作"
                    />
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="预期结果" prop="expect">
                <template slot-scope="scope">
                  <template>
                    <el-input
                      v-model="scope.row.expect"
                      autosize
                      type="textarea"
                      placeholder="预期结果"
                    />
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="remark">
                <template slot-scope="scope">
                  <template>
                    <el-input
                      v-model="scope.row.remark"
                      autosize
                      type="textarea"
                      placeholder="备注"
                    />
                  </template>
                </template>
              </el-table-column>

              <el-table-column align="center" fixed="right" width="150">
                <template slot-scope="scope">
                  <svg-icon icon-class="add" class="clickable-icon mx-10" @click="addStep(scope.$index)" />
                  <svg-icon icon-class="delete" class="clickable-icon mx-10" @click="delStep(scope.$index)" />
                </template>
              </el-table-column>
              <!-- <template slot="empty">
                <el-button type="text" icon="el-icon-plus" @click="addStep(0)">添加步骤</el-button>
              </template> -->
            </el-table>
          </el-form-item>
          <el-form-item>
            <el-button type="text" icon="el-icon-plus" @click="addStep(-1)">添加步骤</el-button>
            <!-- <el-button type="text" icon="el-icon-link" @click="addStep(-1)">引用用例</el-button> -->
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane v-if="caseForm.id > 0" label="版本" name="version">
        <div class="block">
          <el-timeline :reverse="false">
            <el-timeline-item
              v-for="(ver, index) in verOptions"
              :key="index"
              :timestamp="ver.end_time"
              size="large"
              :color="verBtnShow(ver.id) === 0?'#67C23A':''"
              :type="ver.id == caseForm.version_id? 'success': ''"
              :icon="ver.id == caseForm.version_id? 'el-icon-check':''"
              placement="top"
            >
              <div style="width:30%;display: flex; align-items: center;">
                <div style="margin-right: 50px;">
                  <h4>版本：{{ ver.name }}</h4>
                </div>
                <div>
                  <el-button v-if="verBtnShow(ver.id) === 0" type="text" icon="el-icon-refresh" @click="changeVersion(ver.id)">切换</el-button>
                  <el-tooltip class="item" effect="dark" content="基于当前版本，创建一个新版本，进行升级" placement="top">
                    <el-button v-if="verBtnShow(ver.id) === 2" type="text" icon="el-icon-plus" @click="handleNewVersion(ver)">新增</el-button>
                  </el-tooltip>
                  <el-button v-if="verBtnShow(ver.id) === 0" type="text" style="color: #F56C6C;" icon="el-icon-delete" @click="deleteVersion(ver.id)">删除</el-button>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-tab-pane>
      <!-- <el-tab-pane label="缺陷" name="bug">配置管理</el-tab-pane>
      <el-tab-pane label="评审历史" name="review">角色管理</el-tab-pane>
      <el-tab-pane label="执行历史" name="execute">定时任务补偿</el-tab-pane> -->
    </el-tabs>
    <div slot="footer" class="drawer-footer__btn">
      <el-button @click="close()">取 消</el-button>
      <el-button type="primary" @click="save()">保 存</el-button>
    </div>
  </div>
</template>

<script>
import apiVer from '@/api/system/version'
import apiTestcase from '@/api/functional/testcase'
import SelectTree from '@/components/SelectTree'
import Sortable from 'sortablejs'

export default {
  components: { SelectTree },
  props: {
    catalogOptions: {
      type: Array,
      default() {
        return []
      }
    },
    submitType: {
      type: Number,
      default() {
        return 0
      }
    },
    caseForm: {
      type: Object,
      default() {
        return {}
      }
    },
    steps: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      verOptions: [],
      versions: [],
      activeName: 'info',
      caseFormRules: {
        title: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        level: [{ required: true, message: '等级不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
        version_id: [{ required: true, message: '版本不能为空', trigger: 'blur' }],
        catalog_id: [{ required: true, message: '目录不能为空', trigger: 'blur' }]
      },
      oldList: [],
      newList: [],
      sortable: null
    }
  },
  computed: {
    caselibId() {
      return Number(this.$route.query.caselibId)
    },
    levelOptions() {
      return this.$store.state.user.dicts.common_case_level || []
    },
    statusOptions() {
      return this.$store.state.user.dicts.common_case_status.map(option => ({
        ...option,
        value: parseInt(option.value, 10)
      })) || []
    }
  },
  created() {
    this.getVersionOpts()
    this.initSteps()
  },
  methods: {
    initSteps() {
      this.$nextTick(() => {
        this.setSort()
      })
    },
    getVersionOpts() {
      apiVer.getVersionOptions().then(response => {
        this.verOptions = response.data
      })
    },
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.steps.splice(evt.oldIndex, 1)[0]
          this.steps.splice(evt.newIndex, 0, targetRow)
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    },
    addStep(index) {
      // 如果没有传入索引或索引超出数组长度，则默认为数组末尾
      if (typeof index !== 'number' || index < 0 || index >= this.steps.length) {
        index = this.steps.length
      }
      // 在指定索引后插入新步骤
      this.steps.splice(index + 1, 0, {
        id: null,
        testcase_id: this.caseForm.id,
        num: this.steps.length + 1,
        version_id: this.caseForm.version_id,
        action: '',
        expect: '',
        remark: ''
      })
    },
    resortSteps() {
      for (let i = 0; i < this.steps.length; i++) {
        this.steps[i].num = i + 1 // 更新每个步骤的num为当前索引i + 1
      }
    },
    delStep(index) {
      this.steps.splice(index, 1)
    },
    async save() {
      if (this.steps.length === 0) {
        this.$message.error(`请至少添加一个步骤`)
        return
      }
      let hasEmptyValue = false
      let num = 0
      this.steps.forEach((step, index) => {
        if (step.action === '' || step.expect === '') {
          hasEmptyValue = true
          num = index + 1
        }
      })
      if (hasEmptyValue) {
        this.$message.error(`[步骤${num}] 执行动作或预期结果不能为空`)
        return
      }
      await this.$refs.caseForm.validate(async validate => {
        this.resortSteps()
        if (validate) {
          this.caseForm.steps = this.steps
          if (this.submitType === 0) {
            this.caseForm.caselib_id = this.$route.query.caselibId
            this.caseForm.max_version_id = this.caseForm.version_id
            await apiTestcase.createTestcase(this.caseForm).then(response => {
              this.$message.success(response.message || '新增成功')
            }).catch(error => {
              this.$message.error(error.response.data['message'])
            })
          } else {
            await apiTestcase.updateTestcase(this.caseForm).then(response => {
              this.$message.success(response.message || '编辑成功')
            }).catch(error => {
              this.$message.error(error.response.data['message'])
            })
          }
          this.$emit('closeDrawer', { refresh: true })
        }
      })
    },
    close() {
      this.$emit('closeDrawer')
    },
    getTestcaseVersions() {
      apiTestcase.getTestcaseVersions(this.caseForm).then(response => {
        this.versions = response.data
      })
    },
    handleTabClick(tab) {
      switch (tab.name) {
        case 'version':
          this.getTestcaseVersions()
      }
    },
    changeVersion(version_id) {
      this.$confirm('确定要切换至该版本吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        lockScroll: false,
        type: 'warning'
      }).then(async() => {
        const data = {
          id: this.caseForm.id,
          version_id: version_id
        }
        apiTestcase.changeTestcaseVersion(data).then(response => {
          this.$message.success(response.message || '版本切换成功')
          this.$emit('getTestcaseInfo', { testcaseId: this.caseForm.id, versionId: version_id })
          this.$emit('refreshList')
          this.activeName = 'info'
        }).catch(error => {
          this.$message.error(error.response.data['message'])
        })
      })
    },
    verBtnShow(verOptionId) {
      if (this.versions.some(version => version.id === verOptionId)) {
        return verOptionId !== this.caseForm.version_id ? 0 : 1
      } else {
        return 2
      }
    },
    handleNewVersion(version) {
      this.$confirm('确定要创建新版本吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        lockScroll: false,
        type: 'warning'
      }).then(async() => {
        const allVersions = [...this.versions, version]
        let maxOrder = -Infinity
        let maxOrderVersionId = null
        allVersions.forEach(v => {
          if (v.order > maxOrder) {
            maxOrder = v.order
            maxOrderVersionId = v.id
          }
        })

        const data = {
          id: this.caseForm.id,
          version_id: version.id,
          steps: this.steps,
          max_version_id: maxOrderVersionId
        }
        apiTestcase.createNewVersion(data).then(response => {
          this.$message.success(response.message || '版本新增成功')
          this.$emit('getTestcaseInfo', { testcaseId: this.caseForm.id, versionId: version.id })
          this.$emit('refreshList')
          this.activeName = 'info'
        }).catch(error => {
          this.$message.error(error.response.data['message'])
        })
      })
    },
    deleteVersion(versionId) {
      this.$confirm('确定要删除当前版本吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        lockScroll: false,
        type: 'warning'
      }).then(async() => {
        const data = {
          id: this.caseForm.id,
          version_id: versionId
        }
        apiTestcase.deleteTestcaseVersion(data).then(response => {
          this.$message.success(response.message || '版本删除成功')
          this.getTestcaseVersions()
        }).catch(error => {
          this.$message.error(error.response.data['message'])
        })
      })
    }
  }
}
</script>

<style scoped>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}

.drag-handler{
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.wrap-text {
  /* font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif; */
  word-wrap: break-word; /* 允许在单词内换行 */
  white-space: pre-wrap; /* 保留空格和换行符 */
  overflow-wrap: break-word; /* 旧版浏览器兼容性 */
  min-height: 1em; /* 最小高度1行 */
}
</style>
